#include "pdfannotationtoolbar.h"
#include <QColorDialog>
#include <QPainter>
#include <QHBoxLayout>
#include <QFontDatabase>
#include <QLabel>
#include <QMenu>


// ============================================================================
// PDFColorPickerButton 实现
// ============================================================================

PDFColorPickerButton::PDFColorPickerButton(ColorType type, QWidget* parent)
    : QToolButton(parent)
    , m_colorType(type)
    , m_currentColor(type == StrokeColor ? Qt::red : QColor(255, 255, 0, 51))
    , m_menu(nullptr)
{
    if (type == StrokeColor)
        setToolTip(tr("画笔颜色（边框/线条）"));
    else
        setToolTip(tr("画刷颜色（填充）"));

    setPopupMode(QToolButton::MenuButtonPopup);
    setupMenu();
    updateButtonIcon();

    connect(this, &QToolButton::clicked, this, &PDFColorPickerButton::onButtonClicked);
}

void PDFColorPickerButton::setCurrentColor(const QColor& color)
{
    if (m_currentColor != color)
    {
        m_currentColor = color;
        updateButtonIcon();
        Q_EMIT colorChanged(color);
    }
}

void PDFColorPickerButton::setupMenu()
{
    m_menu = new QMenu(this);
    setMenu(m_menu);

    // 预设颜色
    QMenu* presetsMenu = m_menu->addMenu(tr("预设颜色"));

    if (m_colorType == StrokeColor)
    {
        // 画笔颜色预设（不透明）
        presetsMenu->addAction(createColorAction(Qt::red, tr("红色")));
        presetsMenu->addAction(createColorAction(Qt::blue, tr("蓝色")));
        presetsMenu->addAction(createColorAction(Qt::green, tr("绿色")));
        presetsMenu->addAction(createColorAction(Qt::black, tr("黑色")));
        presetsMenu->addAction(createColorAction(Qt::yellow, tr("黄色")));
        presetsMenu->addAction(createColorAction(QColor(255, 165, 0), tr("橙色")));
    }
    else
    {
        // 画刷颜色预设（半透明）
        presetsMenu->addAction(createColorAction(QColor(255, 255, 0, 51), tr("黄色")));
        presetsMenu->addAction(createColorAction(QColor(0, 255, 0, 51), tr("绿色")));
        presetsMenu->addAction(createColorAction(QColor(255, 192, 203, 51), tr("粉色")));
        presetsMenu->addAction(createColorAction(QColor(173, 216, 230, 51), tr("蓝色")));
        presetsMenu->addAction(createColorAction(QColor(255, 165, 0, 51), tr("橙色")));
        presetsMenu->addAction(createColorAction(Qt::transparent, tr("无填充")));
    }

    m_menu->addSeparator();

    // 自定义颜色
    QAction* customColorAction = m_menu->addAction(tr("自定义颜色..."));
    connect(customColorAction, &QAction::triggered, this, &PDFColorPickerButton::onCustomColorSelected);
}

QAction* PDFColorPickerButton::createColorAction(const QColor& color, const QString& name)
{
    QPixmap pixmap(48, 20);
    pixmap.fill(Qt::white);

    QPainter painter(&pixmap);

    // 绘制透明背景网格（如果有透明度）
    if (color.alpha() < 255)
    {
        painter.fillRect(2, 2, 44, 16, Qt::white);
        for (int i = 0; i < 44; i += 4)
        {
            for (int j = 0; j < 16; j += 4)
            {
                if ((i + j) % 8 == 0)
                    painter.fillRect(2 + i, 2 + j, 4, 4, QColor(200, 200, 200));
            }
        }
    }

    // 绘制颜色
    painter.fillRect(2, 2, 44, 16, color);
    painter.setPen(Qt::gray);
    painter.drawRect(2, 2, 44, 16);

    QAction* action = new QAction(QIcon(pixmap), name, this);
    action->setData(color);
    connect(action, &QAction::triggered, this, &PDFColorPickerButton::onPresetColorSelected);

    return action;
}

void PDFColorPickerButton::updateButtonIcon()
{
    QPixmap pixmap(24, 24);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);

    // 绘制透明背景网格
    if (m_currentColor.alpha() < 255)
    {
        painter.fillRect(2, 2, 20, 20, Qt::white);
        for (int i = 0; i < 20; i += 4)
        {
            for (int j = 0; j < 20; j += 4)
            {
                if ((i + j) % 8 == 0)
                    painter.fillRect(2 + i, 2 + j, 4, 4, QColor(200, 200, 200));
            }
        }
    }

    // 绘制颜色
    QRect colorRect(2, 2, 20, 20);
    painter.fillRect(colorRect, m_currentColor);
    painter.setPen(Qt::gray);
    painter.drawRect(colorRect);

    setIcon(QIcon(pixmap));
}

void PDFColorPickerButton::onButtonClicked()
{
    Q_EMIT colorChanged(m_currentColor);
}

void PDFColorPickerButton::onPresetColorSelected()
{
    QAction* action = qobject_cast<QAction*>(sender());
    if (action)
    {
        QColor color = action->data().value<QColor>();
        setCurrentColor(color);
    }
}

void PDFColorPickerButton::onCustomColorSelected()
{
    QColorDialog::ColorDialogOptions options = QColorDialog::DontUseNativeDialog;
    if (m_colorType == FillColor)
        options |= QColorDialog::ShowAlphaChannel;

    QColor newColor = QColorDialog::getColor(m_currentColor, this, tr("选择颜色"), options);

    if (newColor.isValid())
    {
        setCurrentColor(newColor);
    }
}

// ============================================================================
// PDFLineWidthSelector 实现
// ============================================================================

PDFLineWidthSelector::PDFLineWidthSelector(QWidget* parent)
    : QComboBox(parent)
{
    setToolTip(tr("线宽"));
    setupItems();
    connect(this, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &PDFLineWidthSelector::onCurrentIndexChanged);
}

void PDFLineWidthSelector::setupItems()
{
    // 添加常用线宽
    struct LineWidth {
        qreal width;
        QString text;
    };

    QVector<LineWidth> widths = {
        {0.5, tr("0.5 pt (极细)")},
        {1.0, tr("1.0 pt (细)")},
        {1.5, tr("1.5 pt")},
        {2.0, tr("2.0 pt (中等)")},
        {3.0, tr("3.0 pt")},
        {4.0, tr("4.0 pt (粗)")},
        {5.0, tr("5.0 pt")},
        {6.0, tr("6.0 pt (极粗)")},
        {8.0, tr("8.0 pt")},
        {10.0, tr("10.0 pt")}
    };

    for (const auto& item : widths)
    {
        // 创建线宽预览图标
        QPixmap pixmap(50, 20);
        pixmap.fill(Qt::white);
        QPainter painter(&pixmap);
        QPen pen(Qt::black);
        pen.setWidthF(item.width);
        painter.setPen(pen);
        painter.drawLine(5, 10, 45, 10);

        addItem(QIcon(pixmap), item.text, item.width);
    }

    // 默认选择2.0 pt
    setCurrentIndex(3);
}

qreal PDFLineWidthSelector::currentLineWidth() const
{
    return currentData().toReal();
}

void PDFLineWidthSelector::setCurrentLineWidth(qreal width)
{
    for (int i = 0; i < count(); ++i)
    {
        if (qAbs(itemData(i).toReal() - width) < 0.01)
        {
            setCurrentIndex(i);
            return;
        }
    }
}

void PDFLineWidthSelector::onCurrentIndexChanged(int index)
{
    if (index >= 0)
    {
        Q_EMIT lineWidthChanged(currentLineWidth());
    }
}

// ============================================================================
// PDFFontComboBox 实现
// ============================================================================

PDFFontComboBox::PDFFontComboBox(QWidget* parent)
    : QComboBox(parent)
{
    setToolTip(tr("字体"));
    setEditable(false);

    // 添加系统字体
    QFontDatabase fontDatabase;
    QStringList families = fontDatabase.families();
    addItems(families);

    // 设置默认字体
    setCurrentText(QFont().family());

    connect(this, &QComboBox::currentTextChanged, this, &PDFFontComboBox::fontFamilyChanged);
}

QString PDFFontComboBox::currentFontFamily() const
{
    return currentText();
}

void PDFFontComboBox::setCurrentFontFamily(const QString& family)
{
    setCurrentText(family);
}

// ============================================================================
// PDFFontSizeSpinBox 实现
// ============================================================================

PDFFontSizeSpinBox::PDFFontSizeSpinBox(QWidget* parent)
    : QSpinBox(parent)
{
    setToolTip(tr("字体大小"));
    setRange(6, 72);
    setValue(12);
    setSuffix(" pt");

    connect(this, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &PDFFontSizeSpinBox::fontSizeChanged);
}

// ============================================================================
// PDFFontStyleButtons 实现
// ============================================================================

PDFFontStyleButtons::PDFFontStyleButtons(QWidget* parent)
    : QWidget(parent)
{
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(2);

    // 粗体按钮
    m_boldButton = new QToolButton(this);
    m_boldButton->setText(tr("B"));
    m_boldButton->setToolTip(tr("粗体"));
    m_boldButton->setCheckable(true);
    QFont boldFont = m_boldButton->font();
    boldFont.setBold(true);
    m_boldButton->setFont(boldFont);

    // 斜体按钮
    m_italicButton = new QToolButton(this);
    m_italicButton->setText(tr("I"));
    m_italicButton->setToolTip(tr("斜体"));
    m_italicButton->setCheckable(true);
    QFont italicFont = m_italicButton->font();
    italicFont.setItalic(true);
    m_italicButton->setFont(italicFont);

    // 下划线按钮
    m_underlineButton = new QToolButton(this);
    m_underlineButton->setText(tr("U"));
    m_underlineButton->setToolTip(tr("下划线"));
    m_underlineButton->setCheckable(true);
    QFont underlineFont = m_underlineButton->font();
    underlineFont.setUnderline(true);
    m_underlineButton->setFont(underlineFont);

    layout->addWidget(m_boldButton);
    layout->addWidget(m_italicButton);
    layout->addWidget(m_underlineButton);

    connect(m_boldButton, &QToolButton::toggled, this, &PDFFontStyleButtons::onStyleButtonToggled);
    connect(m_italicButton, &QToolButton::toggled, this, &PDFFontStyleButtons::onStyleButtonToggled);
    connect(m_underlineButton, &QToolButton::toggled, this, &PDFFontStyleButtons::onStyleButtonToggled);
}

void PDFFontStyleButtons::setBold(bool bold)
{
    m_boldButton->setChecked(bold);
}

void PDFFontStyleButtons::setItalic(bool italic)
{
    m_italicButton->setChecked(italic);
}

void PDFFontStyleButtons::setUnderline(bool underline)
{
    m_underlineButton->setChecked(underline);
}

void PDFFontStyleButtons::onStyleButtonToggled()
{
    Q_EMIT styleChanged(isBold(), isItalic(), isUnderline());
}

// ============================================================================
// PDFAnnotationToolBar 实现
// ============================================================================

PDFAnnotationToolBar::PDFAnnotationToolBar(QToolBar* toolbar, QObject* parent)
    : QObject(parent)
{
    setupToolBar(toolbar);
}

void PDFAnnotationToolBar::setupToolBar(QToolBar* toolbar)
{
    // 1. 画笔颜色
    QLabel* strokeLabel = new QLabel(tr("边框:"));
    toolbar->addWidget(strokeLabel);

    m_strokeColorButton = new PDFColorPickerButton(PDFColorPickerButton::StrokeColor, toolbar);
    toolbar->addWidget(m_strokeColorButton);
    connect(m_strokeColorButton, &PDFColorPickerButton::colorChanged,
            this, &PDFAnnotationToolBar::strokeColorChanged);

    // 2. 画刷颜色
    QLabel* fillLabel = new QLabel(tr("填充:"));
    toolbar->addWidget(fillLabel);

    m_fillColorButton = new PDFColorPickerButton(PDFColorPickerButton::FillColor, toolbar);
    toolbar->addWidget(m_fillColorButton);
    connect(m_fillColorButton, &PDFColorPickerButton::colorChanged,
            this, &PDFAnnotationToolBar::fillColorChanged);

    // 3. 线宽
    QLabel* lineWidthLabel = new QLabel(tr("线宽:"));
    toolbar->addWidget(lineWidthLabel);

    m_lineWidthSelector = new PDFLineWidthSelector(toolbar);
    toolbar->addWidget(m_lineWidthSelector);
    connect(m_lineWidthSelector, &PDFLineWidthSelector::lineWidthChanged,
            this, &PDFAnnotationToolBar::lineWidthChanged);

    toolbar->addWidget(createSeparator());

    // 4. 文本颜色
    QLabel* textColorLabel = new QLabel(tr("文字:"));
    toolbar->addWidget(textColorLabel);

    m_textColorButton = new PDFColorPickerButton(PDFColorPickerButton::StrokeColor, toolbar);
    m_textColorButton->setCurrentColor(Qt::black);
    toolbar->addWidget(m_textColorButton);
    connect(m_textColorButton, &PDFColorPickerButton::colorChanged,
            this, &PDFAnnotationToolBar::textColorChanged);

    // 5. 字体
    m_fontComboBox = new PDFFontComboBox(toolbar);
    m_fontComboBox->setMinimumWidth(120);
    toolbar->addWidget(m_fontComboBox);
    connect(m_fontComboBox, &PDFFontComboBox::fontFamilyChanged,
            this, &PDFAnnotationToolBar::fontFamilyChanged);

    // 6. 字体大小
    m_fontSizeSpinBox = new PDFFontSizeSpinBox(toolbar);
    toolbar->addWidget(m_fontSizeSpinBox);
    connect(m_fontSizeSpinBox, &PDFFontSizeSpinBox::fontSizeChanged,
            this, &PDFAnnotationToolBar::fontSizeChanged);

    // 7. 字体样式
    m_fontStyleButtons = new PDFFontStyleButtons(toolbar);
    toolbar->addWidget(m_fontStyleButtons);
    connect(m_fontStyleButtons, &PDFFontStyleButtons::styleChanged,
            this, &PDFAnnotationToolBar::fontStyleChanged);
}

QWidget* PDFAnnotationToolBar::createSeparator()
{
    QFrame* separator = new QFrame();
    separator->setFrameShape(QFrame::VLine);
    separator->setFrameShadow(QFrame::Sunken);
    return separator;
}

void PDFAnnotationToolBar::setStrokeColor(const QColor& color)
{
    m_strokeColorButton->setCurrentColor(color);
}

void PDFAnnotationToolBar::setFillColor(const QColor& color)
{
    m_fillColorButton->setCurrentColor(color);
}

void PDFAnnotationToolBar::setLineWidth(qreal width)
{
    m_lineWidthSelector->setCurrentLineWidth(width);
}

void PDFAnnotationToolBar::setTextColor(const QColor& color)
{
    m_textColorButton->setCurrentColor(color);
}

void PDFAnnotationToolBar::setFontFamily(const QString& family)
{
    m_fontComboBox->setCurrentFontFamily(family);
}

void PDFAnnotationToolBar::setFontSize(int size)
{
    m_fontSizeSpinBox->setValue(size);
}

void PDFAnnotationToolBar::setFontStyle(bool bold, bool italic, bool underline)
{
    m_fontStyleButtons->setBold(bold);
    m_fontStyleButtons->setItalic(italic);
    m_fontStyleButtons->setUnderline(underline);
}
